<template>
  <div class="app-container" v-if="commodityForm">
    <el-form :model="commodityForm" :rules="rules" label-width="80px" ref="commodityFormDom">
      <div class="">
        <h1>新增分账接收方</h1>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="分账接收方名称" prop="receiverName" label-width="220">
              <el-input v-model="commodityForm.receiverName" placeholder="请输入分账接收方名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系手机号" prop="contactMobile" label-width="220">
              <el-input v-model="commodityForm.contactMobile" placeholder="请输入联系手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对公对私" prop="acctTypeCode" label-width="220">
              <el-select v-model="commodityForm.acctTypeCode">
                <el-option v-for="item in cashPayList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照号码" prop="licenseNo" label-width="220">
              <el-input v-model="commodityForm.licenseNo" placeholder="请输入营业执照号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照名称" prop="licenseName" label-width="220">
              <el-input v-model="commodityForm.licenseName" placeholder="请输入营业执照名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人姓名(对公必传)" prop="legalPersonName" label-width="220">
              <el-input v-model="commodityForm.legalPersonName" placeholder="请输入联系手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型" prop="legalPersonCertificateType" label-width="220">
              <el-select v-model="commodityForm.legalPersonCertificateType">
                <el-option v-for="item in cateTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人证件号" prop="legalPersonCertificateNo" label-width="220">
              <el-input v-model="commodityForm.legalPersonCertificateNo" placeholder="请输入法人证件号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款卡号" prop="acctNo" label-width="220">
              <el-input v-model="commodityForm.acctNo" placeholder="请输入收款卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户名" prop="acctName" label-width="220">
              <el-input v-model="commodityForm.acctName" placeholder="请输入收款账户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户证件类型" prop="acctCertificateType" label-width="220">
              <el-select v-model="commodityForm.acctCertificateType">
                <el-option v-for="item in cateTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户证件号" prop="acctCertificateNo" label-width="220">
              <el-input v-model="commodityForm.acctCertificateNo" placeholder="请输入收款账户证件号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户开户行号" prop="acctOpenBankCode" label-width="220">
              <el-input v-model="commodityForm.acctOpenBankCode" placeholder="请输入收款账户开户行号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户开户名称" prop="acctOpenBankName" label-width="220">
              <el-input v-model="commodityForm.acctOpenBankName" placeholder="请输入收款账户开户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户清算行行号" prop="acctClearBankCode" label-width="220">
              <el-input v-model="commodityForm.acctClearBankCode" placeholder="请输入收款账户清算行行号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="法人/个人身份证人像面" prop="cover" label-width="220">
            <ImageCropUpload :width="300" :height="200" v-model="commodityForm.frIdCardFront" :isYuji="true"
              :params="{ attType: 'FR_ID_CARD_FRONT' }"></ImageCropUpload>
            <!-- <ImageUpload v-model="commodityForm.icons"></ImageUpload> -->
          </el-form-item>
          <el-form-item label="法人/个人身份证国徽面" prop="cover" label-width="220">
            <ImageCropUpload :width="300" :height="200" v-model="commodityForm.frIdCardBehind" :isYuji="true"
              :params="{ attType: 'FR_ID_CARD_BEHIND' }"></ImageCropUpload>
          </el-form-item>
        </el-row>
      </div>
    </el-form>

    <div class="footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
<script setup name="CommodityAdd">
import { reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { childrenByCode } from "@/api/system/type";
import { listMoney } from "@/api/money/money";
import { innerList } from "@/api/mall/mallSpec";
import {
  addMallSpu,
  updateMallSpu,
  getMallSpu,
  innerListMallSpu,
  applyLedgerReceiver,
} from "@/api/mall/mallSpu";
import { Plus } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const currency = ref([]);
const currencySendList = ref([]);
const zichanTypeList = ref([]);

function getCurrency(name) {
  innerListMallSpu({
    name,
    columnType: 12,
  }).then((res) => {
    currencySendList.value = res.data;
  });
}

getCurrency("");
const spuCashMoneyList = ref([]);
const giveTypeList = ref([
  {
    label: "赠送数量",
    value: 0,
  },
  {
    label: "赠送比例",
    value: 1,
  },
]);
const ueditorConfig = ref({
  // 编辑器不自动被内容撑高
  autoHeightEnabled: true,
  // 初始容器高度
  initialFrameHeight: 400,
  // 初始容器宽度
  initialFrameWidth: "100%",
  UEDITOR_HOME_URL: "/ueditor/",
});
const pageType = ref(1);
const specificationList = ref([]);
const preTypeArr = ref([]);

async function getPreType() {
  const res = await childrenByCode({
    code: "FUHUA",
  });
  preTypeArr.value = res.data;
}

getPreType();

const mathTypeOneArr = ref([]);
const mathTypeTwoArr = ref([]);

async function getMathType() {
  const res = await childrenByCode({
    code: "SHUZIGUAN",
  });
  mathTypeOneArr.value = res.data;
}

getMathType();

async function getMathTypeTwoArr(e) {
  commodityForm.value.mathTypeTwo = "";
  let index = mathTypeOneArr.value.findIndex(
    (item) => item.id == commodityForm.value.mathTypeOne
  );
  if (index == -1) {
    return;
  }
  const res = await childrenByCode({
    code: mathTypeOneArr.value[index].code,
  });
  mathTypeTwoArr.value = res.data;
}

const commercialSpecification = ref([]);
const tempSpecValue = ref("");
const tempSpecIndex = ref(0);
const productsSkus = ref([]);
const classification = ref([]);
const zhekouArr = ref([]);
const payTypeArr = ref([
  {
    label: "金积分",
    value: 1,
  },
  {
    label: "功德金",
    value: 2,
  },
]);

const columnTypeArr = ref([
  {
    label: "金积分达人",
    value: 1,
  },
  {
    label: "社群达人",
    value: 2,
  },
  {
    label: "本地生活",
    value: 3,
  },
  {
    label: "创业合伙人",
    value: 4,
  },
  {
    label: "消费增值区",
    value: 5,
  },
  {
    label: "熵豆兑换专区",
    value: 6,
  },
  {
    label: "创业联盟区",
    value: 7,
  },
  {
    label: "跨国商贸",
    value: 8,
  },
  {
    label: "社区数字店",
    value: 10,
  },
  {
    label: "趣味消费节",
    value: 11,
  },
  {
    label: "商品折扣券",
    value: 12,
  },
  {
    label: "资产包",
    value: 13,
  },
]);

const storeId = ref(null);

const data = reactive({
  commodityForm: {},
  rules: {
    receiverName: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    contactMobile: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    acctTypeCode: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    // licenseNo: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    // licenseName: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    // licenseName: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    // legalPersonName: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    // legalPersonCertificateType: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    // legalPersonCertificateNo: [
    //   {
    //     required: true,
    //     message: "请填写商品详情",
    //     trigger: "change",
    //   },
    // ],
    acctNo: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    acctCertificateType: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    acctCertificateNo: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    acctOpenBankCode: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
    frIdCardFront: [
      {
        required: true,
        message: "请上传身份证人像面",
        trigger: "change",
      },
    ],
    frIdCardBehind: [
      {
        required: true,
        message: "请上传身份证国徽面",
        trigger: "change",
      },
    ]
    ,
    acctOpenBankName: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    FR_ID_CARD_BEHIND: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    acctName: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    acctClearBankCode: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    icons: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    detail: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
  },
});

const cashPayList = ref([
  {
    label: "对公",
    value: 57,
  },
  {
    label: "对私",
    value: 58,
  },
]);

const cateTypeList = ref([
  {
    label: "身份证",
    value: 17,
  },
  {
    label: "护照",
    value: 18,
  },
  {
    label: "港澳居民来往内地通行证",
    value: 19,
  },
  {
    label: "台湾居民来往内地通行证",
    value: 20,
  },
]);


const { commodityForm, rules } = toRefs(data);

// 抵扣券
const mallSpuSendsObj = ref({
  voucherId: "", //货币id
  num: "", //赠送的数量/比例
});

// 货币支付定义
const mallSpuMoneyPays = ref({
  moneyId: "", //货币id
  rate: "", //支付比例
});

onMounted(() => {
  route.query.storeId && (storeId.value = route.query.storeId);

  getCommodityType();
  reset();
});

function reset() {
  if (route.query?.id) {
    getMallSpu(route.query?.id).then((res) => {
      productsSkus.value = res.data.mallSkus;
      commodityForm.value = {
        ...res.data,
        mallSpuVoucherList: res.data.mallSpuVoucherList
          ? res.data.mallSpuVoucherList
          : [],
      };
      console.log(commodityForm.value);
    });
  } else {
    commodityForm.value = {

    };
    route.query.columnType &&
      (commodityForm.value.columnType = Number(route.query.columnType));
    proxy.resetForm("commodityFormDom");
  }
}

const getCommodityType = async () => {
  const res = await childrenByCode({
    code: "classification",
  });
  console.log(res, "商品分类");
  classification.value = res.data;

  const zhichanType = await childrenByCode({
    code: "zichanbao_type",
  });

  zichanTypeList.value = zhichanType.data;

  const res2 = await childrenByCode({
    code: "zhekoutaopiaoqu",
  });
  console.log(res2, "折扣");
  zhekouArr.value = res2.data;

  const res4 = await listMoney();
  console.log(res4, "货币");
  currency.value = res4.rows;

  spuCashMoneyList.value = JSON.parse(JSON.stringify(res4.rows));
};

/**
 * 新增货币
 */
const addMoneyPay = () => {
  commodityForm.value.mallSpuConfig.mallSpuMoneyPays.push(
    JSON.parse(JSON.stringify(mallSpuMoneyPays.value))
  );
};

// 删除货币 是否支持现金货币支付
const deletecashMoneyPay = (index) => {
  commodityForm.value.mallSpuConfig.mallSpuCashMoneyPays.splice(index, 1);
};

/**
 * 新增货币 是否支持现金货币支付
 */
const addCashMoneyPay = () => {
  commodityForm.value.mallSpuConfig.mallSpuCashMoneyPays.push(
    JSON.parse(JSON.stringify(mallSpuMoneyPays.value))
  );
};

// 删除货币
const deletePays = (index) => {
  commodityForm.value.mallSpuConfig.mallSpuMoneyPays.splice(index, 1);
};

// 监听已有货币 有则选择禁用
// watch(
//   () => commodityForm.value.mallSpuConfig?.mallSpuMoneyPays,
//   (newVal) => {
//     for (let i = 0; i < currency.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.moneyId === currency.value[i].id;
//       });
//       if (Index != -1) {
//         currency.value[i].disabled = true;
//       } else {
//         currency.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 监听已有货币 有则选择禁用
// watch(
//   () => commodityForm.value.mallSpuConfig?.mallSpuCashMoneyPays,
//   (newVal) => {
//     for (let i = 0; i < spuCashMoneyList.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.moneyId === spuCashMoneyList.value[i].id;
//       });
//       if (Index != -1) {
//         spuCashMoneyList.value[i].disabled = true;
//       } else {
//         spuCashMoneyList.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 新增赠送
const addSendMoney = () => {
  commodityForm.value.mallSpuVoucherList.push(
    JSON.parse(JSON.stringify(mallSpuSendsObj.value))
  );
};

// 删除赠送
const deleteSend = (index) => {
  commodityForm.value.mallSpuVoucherList.splice(index, 1);
};

// 监听已有货币 有则选择禁用
watch(
  () => commodityForm.value?.mallSpuVoucherList,
  (newVal) => {
    if (commodityForm.value?.mallSpuVoucherList) {
      console.log(newVal, "newVal");
      for (let i = 0; i < currencySendList.value.length; i++) {
        const Index = newVal.findIndex((item) => {
          return item.voucherId === currencySendList.value[i].id;
        });
        if (Index != -1) {
          currencySendList.value[i].disabled = true;
        } else {
          currencySendList.value[i].disabled = false;
        }
      }
    }
  },
  { deep: true }
);

const remoteMethod = async (e) => {
  const res = await innerList({
    name: e,
  });
  specificationList.value = res.data;
};
remoteMethod("");

// 添加规格
const addSpecification = () => {
  if (commercialSpecification.value.length > 1) {
    proxy.$modal.msg("最多添加俩种商品属性!");
  } else {
    commercialSpecification.value.push({
      specId: "",
      specName: "",
      specValue: [],
      tempIsSpec: true,
    });
  }
  calculateProductsSkus();
};

const specificationChange = (item) => {
  specificationList.value.forEach((i) => {
    if (item.specId == i.id) {
      item.specName = i.name;
    }
  });
};

// 添加规格值
const addspecValue = (index) => {
  tempSpecIndex.value = index;
  tempSpecValue.value = "";
  commercialSpecification.value[index].tempIsSpec = false;
};

const confirmSpec = (index) => {
  commercialSpecification.value[index].specValue.push(tempSpecValue.value);
  commercialSpecification.value[index].tempIsSpec = true;
  calculateProductsSkus();
};

const handleClose = (item, index) => {
  item.splice(index, 1);
  calculateProductsSkus();
};

const deleteSpec = (index) => {
  commercialSpecification.value.splice(index, 1);
  calculateProductsSkus();
};

// 判断选过的商品属性不能再选
// watch(
//   () => commercialSpecification.value,
//   (newVal) => {
//     for (let i = 0; i < specificationList.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.specId === specificationList.value[i].id;
//       });
//       if (Index != -1) {
//         specificationList.value[i].disabled = true;
//       } else {
//         specificationList.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 计算productsSkus
const calculateProductsSkus = () => {
  // 判断commercialSpecification是否为空,为空则productsSkus空
  if (commercialSpecification.value.length == 0) {
    productsSkus.value = [];
    return;
  }

  // 循环商品规格数组
  for (let i = 0; i < commercialSpecification.value.length; i++) {
    if (commercialSpecification.value[i].specId == "") {
      productsSkus.value = [];
      return;
    }
    // 循环内部规格值数组 如果规格值数组为空则productsSkus空
    if (commercialSpecification.value[i].specValue.length == 0) {
      productsSkus.value = [];
      return;
    }
  }

  productsSkus.value = [];

  // 如果有值则开始计算productsSkus的值
  // 判断商品规格数组长度 如果等于1 则只需走一层循环
  if (commercialSpecification.value.length == 1) {
    commercialSpecification.value[0].specValue.forEach((i, j) => {
      productsSkus.value.push({
        id: j + 1,
        xiaofeijinPrice: 0, //原价
        sendJinjifenNum: 0, //原价
        sendShangdouPrice: 0,
        price: 0, //现价
        icons: "", //图片
        stock: 0, //库存
        mallSkuSpecs: [
          //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
          {
            specId: commercialSpecification.value[0].specId, //商品规格id
            specName: commercialSpecification.value[0].specName, //为了页面展示需要规格类型名
            specValue: i, //商品规格值
          },
        ],
      });
    });
  }

  // 判断商品规格数组长度 如果等于2 则只需走俩层循环
  if (commercialSpecification.value.length == 2) {
    commercialSpecification.value[0].specValue.forEach((i, j) => {
      commercialSpecification.value[1].specValue.forEach((item, index) => {
        productsSkus.value.push({
          id: j + 1,
          xiaofeijinPrice: 0, //原价
          sendJinjifenNum: 0, //原价
          price: 0, //现价
          icons: "", //图片
          stock: 0, //库存
          mallSkuSpecs: [
            //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
            {
              specId: commercialSpecification.value[0].specId, //商品规格id
              specName: commercialSpecification.value[0].specName, //为了页面展示需要规格类型名
              specValue: i, //商品规格值
            },
            {
              specId: commercialSpecification.value[1].specId, //商品规格id
              specName: commercialSpecification.value[1].specName, //为了页面展示需要规格类型名
              specValue: item, //商品规格值
            },
          ],
        });
      });
    });
  }
};

const cancel = () => {
  router.go(-1);
};

const submitForm = () => {
  proxy.$refs["commodityFormDom"].validate((valid) => {
    if (valid) {
      if (commodityForm.value.id) {
        updateMallSpu({
          ...commodityForm.value,
        }).then((res) => {
          console.log(res, "修改商品");
          proxy.$modal.msgSuccess("修改商品");
          cancel();
        });
      } else {
        let apiForm = {
          ...commodityForm.value,
          // storeId: storeId.value,
        };
        applyLedgerReceiver(apiForm).then((res) => {
          console.log("🚀🚀🚀 ~ applyLedgerReceiver ~ res:", res)
          proxy.$modal.msgSuccess("添加成功");
          cancel();
        });
      }
    } else {
      proxy.$modal.msg("请完整填写必填信息!");
    }
  });
};
</script>

<style lang="scss" scoped>
.mb-16 {
  margin-bottom: 16px;
}

.mb-32 {
  margin-bottom: 32px;
}

.footer {
  text-align: center;
  margin-top: 50px;
}

.specification_wrap {
  padding: 32px;
  border: 1px solid #e5e5e5;
  background: #fcfcfc;
  margin-top: 16px;
  border-radius: 4px;
  justify-content: space-between;
}

.specValue {
  display: flex;
  align-items: center;
}

:deep(.el-tag--default) {
  margin-left: 8px;
}
</style>
